package com.sghj.SysPermission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sghj.SysPermission.entity.*;
import com.sghj.SysPermission.entity.Vo.roleAddVo;
import com.sghj.SysPermission.mapper.SysRoleDeptMapper;
import com.sghj.SysPermission.mapper.SysRoleMapper;
import com.sghj.SysPermission.service.SysRoleService;
import com.sghj.SysPermission.service.SysRolemenuService;
import com.sghj.SysPermission.service.SysUserroleService;
import com.sghj.config.handler.ResultCode;
import com.sghj.config.handler.exceptionHandler.MyException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xrx
 * @since 2022-02-18
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRolemenuService rolemenuService;
    @Autowired
    private SysUserroleService userroleService;
    @Autowired
    private SysRoleDeptMapper roleDeptMapper;



    /**
     * 添加角色
     * @param role
     * @return
     */
    @Override
    @Transactional
    public int addRole(roleAddVo role) {
        if (role.getSysRoleName()!=null&&baseMapper.selectCount(new QueryWrapper<SysRole>().eq("SysRoleName", role.getSysRoleName()))>0){
            throw new MyException(ResultCode.PARAMETER,"该角色名已存在");
        }
        //if (role.getRoleKey()!=null&&!ValidateUtil.isStrEnglish(role.getRoleKey())){
        //    throw new MyException(ResultCode.PARAMETER,"权限字符仅可为英文");
        //}
        if (role.getRoleKey()!=null&&baseMapper.selectCount(new QueryWrapper<SysRole>().eq("role_key",role.getRoleKey()).ne("SysRoleId",role.getSysRoleId()))>0){
            throw new MyException(ResultCode.PARAMETER,"该权限字符已存在");
        }
        //添加角色
        SysRole newRole = new SysRole();
        BeanUtils.copyProperties(role,newRole);
        int insert = baseMapper.insert(newRole);
        //添加角色-权限关联信息
        if (role.getMenuIds()!=null&&role.getMenuIds().length>0) {
            addRoleMenu(role, newRole);
        }
        return insert;
    }

    /**
     * 根据id删除角色
     * @param rid
     * @return
     */
    @Override
    @Transactional
    public int removeRoleById(Integer rid) {
        //删除角色信息
        int delete = baseMapper.deleteById(rid);
        //删除用户-角色关联信息
        userroleService.remove(new QueryWrapper<SysUserrole>().eq("SysRoleId",rid));
        //删除角色-权限关联信息
        rolemenuService.remove(new QueryWrapper<SysRolemenu>().eq("SysRoleId",rid));
        ////删除角色-数据权限关联信息
        //rolegroupService.remove(new QueryWrapper<SysRolegroup>().eq("sysRoleId",rid));

        return delete;
    }

    /**
     * 修改角色信息
     * @param role
     * @return
     */
    @Override
    @Transactional
    public int updateRole(roleAddVo role) {
        if (role.getSysRoleName()!=null&&baseMapper.selectCount(new QueryWrapper<SysRole>().eq("SysRoleName", role.getSysRoleName()).ne("SysRoleId",role.getSysRoleId()))>0){
            throw new MyException(ResultCode.PARAMETER,"该角色名已存在");
        }
        //if (role.getRoleKey()!=null&&!ValidateUtil.isStrEnglish(role.getRoleKey())){
        //    throw new MyException(ResultCode.PARAMETER,"权限字符仅可为英文");
        //}
        if (role.getRoleKey()!=null&&baseMapper.selectCount(new QueryWrapper<SysRole>().eq("role_key",role.getRoleKey()).ne("SysRoleId",role.getSysRoleId()))>0){
            throw new MyException(ResultCode.PARAMETER,"该权限字符已存在");
        }
        //修改角色信息
        SysRole newRole = new SysRole();
        BeanUtils.copyProperties(role,newRole);
        int update = baseMapper.updateById(newRole);
        if (update<1){
            throw new MyException(ResultCode.FAIL,"修改角色信息失败了..");
        }
        //如果进行权限修改
        if (role.getMenuIds()!=null) {
            //删除角色-权限信息
            rolemenuService.remove(new QueryWrapper<SysRolemenu>().eq("SysRoleId", role.getSysRoleId()));
            //添加角色-权限信息
            addRoleMenu(role, newRole);
        }
        return update;
    }

    /**
     * 查询角色信息
     * @param rid
     * @return
     */
    @Override
    public roleAddVo getRoleById(Integer rid) {
        //查询角色信息
        SysRole sysRole = baseMapper.selectById(rid);
        if (sysRole==null){
            throw new MyException(ResultCode.NOTQUERIED,"该用户不存在");
        }
        roleAddVo role= new roleAddVo();
        BeanUtils.copyProperties(sysRole,role);
        //根据id查询角色-权限信息
        int[] menus = getRoleMenuByRid(rid);
        role.setMenuIds(menus);
        return role;
    }

    /**
     * 条件分页查询角色信息
     * @param page
     * @param roleVo
     * @return
     */
    @Override
    //@DataScope(deptAlias = "d")
    public IPage<SysRole> getRolePage(SysRole roleVo,IPage<SysRole> page) {
        return baseMapper.selectRoleList(page,roleVo);

    }

    /**
     * 给角色
     * @return
     */
    @Override
    @Transactional
    public boolean allocatMenus(Integer rid,int[] menus) {
        //删除原有权限
        rolemenuService.remove(new QueryWrapper<SysRolemenu>().eq("SysRoleId",rid));
        //新增新的权限
        List<SysRolemenu> rolemenuList = new ArrayList<>();
        for (int menu : menus) {
            SysRolemenu rolemenu = new SysRolemenu();
            rolemenu.setSysRoleId(rid);
            rolemenu.setMenuId(menu);
            rolemenuList.add(rolemenu);
        }
        return rolemenuService.saveBatch(rolemenuList);
    }

    /**
     *
     * @param uid
     * @return
     */
    @Override
    public List<SysRole> getUserRoleList(Integer uid) {
        return baseMapper.getRoleListByUid(uid);
    }

    /**
     * 分配数据权限
     * @param
     * @return
     */
    @Override
    @Transactional
    public int allocatDataScope(SysRole role) {
        // 修改角色信息
        baseMapper.updateRole(role);
        // 删除角色与部门关联
        baseMapper.deleteRoleDeptByRoleId(role.getSysRoleId());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role);
    }

    /**
     * 插入角色部门关联表
     * @param role
     * @return
     */
    private int insertRoleDept(SysRole role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Integer deptId : role.getDeptIds())
        {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getSysRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 获取角色的门禁权限
     * @param rid
     * @return
     */
    @Override
    public String[] getBuildScopeListByRole(Integer rid) {
        return baseMapper.getBuildScopeByUser(rid);
    }

    /**
     * 根据roleid查询该角色权限
     * @param rid
     * @return
     */
    private int[] getRoleMenuByRid(Integer rid) {
        List<SysRolemenu> sysRoleId = rolemenuService.list(new QueryWrapper<SysRolemenu>().eq("SysRoleId", rid));
        int[] menus = new int[sysRoleId.size()];
        int i =0;
        for (SysRolemenu sysRolemenu : sysRoleId) {
            menus[i++] = sysRolemenu.getMenuId();
        }
        return menus;
    }

    /**
     * 添加角色-权限关联信息
     * @param role
     */
    private void addRoleMenu(roleAddVo role,SysRole newRole) {

        int[] menuIds = role.getMenuIds();
        if (menuIds.length>0){
            // 新增用户与角色管理
            List<SysRolemenu> list = new ArrayList<SysRolemenu>();
            for (Integer menu : menuIds)
            {
                SysRolemenu ur = new SysRolemenu();
                ur.setSysRoleId(newRole.getSysRoleId());
                ur.setMenuId(menu);
                list.add(ur);
            }
            if (list.size()>0){
                rolemenuService.saveBatch(list);
            }
        }
    }
}
